package com.laiat.yamba.activity;

import twitter4j.GeoLocation;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.laiat.yamba.R;
import com.laiat.yamba.YambaApplication;

public class StatusActivity extends BaseActivity implements OnClickListener, TextWatcher, LocationListener {

	private static final String TAG = StatusActivity.class.getSimpleName();
	
	private static final long LOCATION_MIN_TIME = 3600000;  // one hour
	private static final float LOCATION_MIN_DISTANCE = 1000; // one kilometer
	
	private int warningColor;
	private int maxStatusLength;
	private int warningThreshold;
	private int criticalThreshold;
	
	private EditText editText;
	private Button updateButton;
	private TextView textCount;

	private LocationManager locationManager;
	private Location location;
	private String provider;
	
	private ProgressDialog progressDialog;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.status);
        
        //Set integer constants from resources
        warningColor = getResources().getColor(R.color.status_edit_text_warning_color);
        maxStatusLength = getResources().getInteger(R.integer.maxStatusLength);
        criticalThreshold = getResources().getInteger(R.integer.criticalStatusThreshold);
        warningThreshold = getResources().getInteger(R.integer.warningStatusThreshold);
        
        // Find views
        editText = (EditText)findViewById(R.id.editText);
        updateButton = (Button)findViewById(R.id.buttonUpdate);
        
        updateButton.setOnClickListener(this);
        
        textCount = (TextView)findViewById(R.id.textCount);
        textCount.setText(Integer.toString(maxStatusLength));
        textCount.setTextColor(Color.GREEN);

        ImageView userTypeImg = (ImageView)findViewById(R.id.userTypeImg);
        userTypeImg.setImageResource(ActivityManager.isUserAMonkey() ? R.drawable.monkey : R.drawable.person);
           
        editText.addTextChangedListener(this);
//        editText.setFilters(new InputFilter[] {	new InputFilter.LengthFilter(maxStatusLength) });
        
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        String lastStatus = sharedPreferences.getString("status", "NO status saved yet");
        
        Toast.makeText(StatusActivity.this, lastStatus, Toast.LENGTH_LONG).show();
        
    }
    
	@Override
	protected void onResume() {
		super.onResume();

		// setup location info
		provider = yamba.getProvider();
		if (YambaApplication.LOCATION_PROVIDER_NONE.equals(provider)) {
			locationManager = null;
		} else {
			locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
		}
		
		if (locationManager != null) {
			location = locationManager.getLastKnownLocation(provider);
			locationManager.requestLocationUpdates(provider, LOCATION_MIN_TIME, LOCATION_MIN_DISTANCE, this);
		}
	
	}

	@Override
	protected void onPause() {
		super.onPause();
		
		if (locationManager != null) {
			locationManager.removeUpdates(this);
		}
	}




	//called when button is clicked
	@Override
	public void onClick(View v) {
		
		String status = editText.getText().toString();
		
		SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putString("status", status);
		editor.commit();
		
		Twitter twitter = yamba.getTwitter();
		if (twitter == null) {
			//FIXME:  save status so that it is posted when we come back after successful login
			showDialog(DIALOG_TWITTER_LOGIN);
		} else {
			new PostToTwitter().execute(status);
		}
		Log.d(TAG, "onClicked");
		
	}
	
	//Async post to twitter
	class PostToTwitter extends AsyncTask<String, Integer, String> {

		//called to initiate background activity
		@Override
		protected String doInBackground(String... statuses) {

			try {
				YambaApplication yamba = ((YambaApplication) getApplication());
								
				Twitter twitter = yamba.getTwitter();
				if (twitter == null) {
					Log.e(TAG, "twitter is null.");
					return getString(R.string.errorPostFailed);
				}
				//check if we have the location
				StatusUpdate statusUpdate = new StatusUpdate(statuses[0]);
				if (location != null) {
					Log.d(TAG, "Setting location...");
					statusUpdate.location(new GeoLocation(location.getLatitude(), location.getLongitude()));
				}

				twitter4j.Status status = twitter.updateStatus(statusUpdate);
				return status.getText();
			} catch(TwitterException e) {
				Log.e(TAG, "TwitterException updating status", e);
				
				yamba.processTwitterException(e);
				
				return getString(R.string.errorPostFailed);
			} catch(NullPointerException e) {
				Log.e(TAG, "NullPointerException updating status", e);
				
				return getString(R.string.errorPostFailed);				
			} catch(Throwable e) {
				Log.e(TAG, "Throwable updating status", e);
			}
			
			return statuses[0];
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			if(values[0] == 0) {
				progressDialog = ProgressDialog.show(StatusActivity.this, "Swirllly...", "Now we wait");
			} else if (values[0] == 1) {
				progressDialog.cancel();
			} else {
				progressDialog.setMessage(String.valueOf(values[0]));
			}
		}
		
		//called when there's a status to be updated
		@Override
		protected void onPostExecute(String result) {
			Toast.makeText(StatusActivity.this, result, Toast.LENGTH_LONG).show();
		}
	}


	@Override
	public void afterTextChanged(Editable statusText) {
		int count = maxStatusLength - statusText.length();
		updateButton.setEnabled(count < 0 ? false : true);
		
		textCount.setText(Integer.toString(count));
		textCount.setTextColor(Color.GREEN);
		if (count < warningThreshold) {
			textCount.setTextColor(warningColor);
		}
		
		if (count < criticalThreshold) {
			textCount.setTextColor(Color.RED);
		}
		
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// do nothing
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// do nothing
		
	}
	

	@Override
	public void onLocationChanged(Location location) {
		Log.d(TAG, "Location changed");
		this.location = location;
	}

	@Override
	public void onProviderDisabled(String provider) {
		if (this.provider.equals(provider)) {
			locationManager.removeUpdates(this);
		}
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		if (this.provider.equals(provider)) {
			locationManager.requestLocationUpdates(this.provider, LOCATION_MIN_TIME, LOCATION_MIN_DISTANCE, this);
		}
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// ignore
	}

	public int getMaxStatusLength() {
		return maxStatusLength;
	}

	public int getWarningColor() {
		return warningColor;
	}

	public int getWarningThreshold() {
		return warningThreshold;
	}

	public int getCriticalThreshold() {
		return criticalThreshold;
	}

	
	
    
} 